# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class BlogsPipeline:
    def __init__(self):
        self.conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="123456", database="blade2",
                                    charset='utf8')
        # 使用 cursor() 方法创建一个游标对象 cursor
        self.cursor = self.conn.cursor()

    def close_spider(self, spider):
        print('----------关闭数据库资源-----------')
        # 关闭游标
        self.cursor.close()
        # 关闭连接
        self.conn.close()
    def process_item(self, item, spider):
        if 'tag' not in item:
            item['tag'] = ''
        insert_sql = """
                    insert into blogs(title,content, tag,view_num,`type`) value(%s,%s,%s,%s,%s)
                    """
        self.cursor.execute(insert_sql, (item['title'], item['content'], item['tag'], item['view_num'], item['type']))
        self.conn.commit()
        return item
